package cn.b.training.baby_education_training.api;

import cn.b.training.baby_education_training.entity.Vaccine;
import cn.b.training.baby_education_training.repository.VaccineRepository;
import cn.b.training.baby_education_training.service.VaccineService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @program: baby_education_training
 * @description
 * @author: wuying
 * @create: 2022-12-02 11:58
 **/
@RestController
@RequestMapping("/vaccine")
public class VaccineController {
    @Autowired
    private VaccineService vaccineService;
    @Autowired
    private VaccineRepository vaccineRepository;

    @PostMapping
    public ResponseEntity addVaccine(@Valid Vaccine vaccine){
        try {
            boolean b = vaccineService.addVaccine(vaccine);
            if (b){
                JSONObject result = new JSONObject();
                result.put("success","添加成功");
                return ResponseEntity.ok(result);
            }else {
                JSONObject error = new JSONObject();
                error.put("failed","添加失败");
                return ResponseEntity.status(400).body(error);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject error = new JSONObject();
            error.put("error",e.getMessage());
            return ResponseEntity.status(400).body(error);
        }
    }


    @DeleteMapping
    public ResponseEntity deleteVaccineById(Long id){
        try {
            boolean b = vaccineService.deleteVaccineById(id);
            if (b) {
                JSONObject result = new JSONObject();
                result.put("success", "删除成功");
                return ResponseEntity.ok(result);
            }else {
                JSONObject error = new JSONObject();
                error.put("failed","删除失败");
                return ResponseEntity.status(400).body(error);
            }
        }catch (Exception e){
            e.printStackTrace();
            JSONObject error = new JSONObject();
            error.put("error",e.getMessage());
            return ResponseEntity.status(400).body(error);
        }
    }

    @GetMapping("/all")
    public ResponseEntity getVaccines() {

        return ResponseEntity.ok(ResponseEntity.ok(vaccineRepository.findAll()));
    }

    @GetMapping("/id")
    public ResponseEntity getVaccines(@RequestParam Long id) {

        return ResponseEntity.ok(ResponseEntity.ok(vaccineRepository.findById(id)));
    }
}
